﻿Imports System.Runtime.CompilerServices
Imports System.Web.Mvc

Namespace Helper

    Public Module RadioButtonListExtensions

        <Extension()> _
        Public Function RadioButtonList(
                                       ByVal helper As HtmlHelper,
                                       ByVal name As String,
                                       ByVal selectList As IEnumerable(Of SelectListItem),
                                       ByVal htmlAttributes As Object) As MvcHtmlString
            Dim ItemString As String = String.Join(" ", selectList.Select(
                    Function(item) String.Format(
                        "<input type=""radio"" name=""{3}"" id=""radio-{0}"" value=""{0}"" {2}/><label for=""radio-{0}"">{1}</label>",
                        IIf(String.IsNullOrEmpty(item.Value), item.Text, item.Value), item.Text, IIf(item.Selected, "checked = ""checked""", ""), name)))

            Dim tagBuilder As TagBuilder = New TagBuilder("div")
            tagBuilder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes))
            tagBuilder.MergeAttribute("name", name, True)
            tagBuilder.MergeAttribute("id", name, True)
            tagBuilder.MergeAttribute("class", "radio-button-list", True)
            tagBuilder.SetInnerText(ItemString)

            Return New MvcHtmlString(HttpUtility.HtmlDecode(tagBuilder.ToString(TagRenderMode.Normal)))
        End Function

    End Module

End Namespace
